package com.tang.common.config;

import cn.hutool.core.util.StrUtil;
import com.tang.common.properties.ElasticSearchProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * ES连接配置类
 * @author tang
 * @date 2021/11/02 13:30
 */
@Slf4j
@Configurable
@EnableConfigurationProperties(ElasticSearchProperties.class)
@ConditionalOnProperty(prefix = "elasticsearch",name = "enable",havingValue = "true")
public class ElasticSearchConfiguration {


    @Resource
    private ElasticSearchProperties elasticSearchProperties;


    @Bean("restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        log.info("ElasticSearch连接地址为 : {}",elasticSearchProperties.getAddress());
        // 拆分地址
        List<HttpHost> hostLists = new ArrayList<>();
        String[] hostList = elasticSearchProperties.getAddress().split(",");
        for (String addr : hostList) {
            String host = addr.split(":")[0];
            String port = addr.split(":")[1];
            hostLists.add(new HttpHost(host, Integer.parseInt(port), elasticSearchProperties.getSchema()));
        }

        final CredentialsProvider credpojoialsProvider = new BasicCredentialsProvider();
        if (StrUtil.isNotBlank(elasticSearchProperties.getUsername())){
            credpojoialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticSearchProperties.getUsername(), elasticSearchProperties.getPassword()));
        }
        // 转换成 HttpHost 数组
        HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
        // 构建连接对象
        RestClientBuilder builder = RestClient.builder(httpHost);
        // 异步连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(elasticSearchProperties.getConnectTimeout());
            requestConfigBuilder.setSocketTimeout(elasticSearchProperties.getSocketTimeout());
            requestConfigBuilder.setConnectionRequestTimeout(elasticSearchProperties.getConnectionRequestTimeout());
            return requestConfigBuilder;
        });
        // 异步连接数配置
        builder.setHttpClientConfigCallback(httpClipojoBuilder -> {
            httpClipojoBuilder.setMaxConnTotal(elasticSearchProperties.getMaxConnectNum());
            httpClipojoBuilder.setMaxConnPerRoute(elasticSearchProperties.getMaxConnectPerRoute());
            return httpClipojoBuilder.setDefaultCredentialsProvider(credpojoialsProvider);
        });
        return new RestHighLevelClient(builder);

    }

}
